import 'dart:convert';

import 'package:dimi_connect/bean/login_entity.dart';
import 'package:dimi_connect/bean/url_bean.dart';
import 'package:dimi_connect/http/Api.dart';
import 'package:dimi_connect/login.dart';
import 'package:dimi_connect/util/bridge.dart';
import 'package:dimi_connect/util/view_creator.dart';
import 'package:dimi_connect/view/loading_dialog.dart';
import 'package:flutter/foundation.dart'
    show debugDefaultTargetPlatformOverride;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia;
  //???
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: FormTestRoute(),
    );
  }
}

class FormTestRoute extends StatefulWidget {
  @override
  _FormTestRouteState createState() => new _FormTestRouteState();
}

class _FormTestRouteState extends State<FormTestRoute> {
  TextEditingController _ipController = new TextEditingController();
  TextEditingController _userController = new TextEditingController();
  GlobalKey _formKey = new GlobalKey<FormState>();

  Widget build(BuildContext context) {
    var view = Scaffold(
        appBar: AppBar(
          title: Text("DiMi轻松连"),
          actions: [
            PopupMenuButton(
                onSelected: (String value) {
                  setState(() {
                    Bridge.openUrl(value);
                  });
                },
                itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
                      new PopupMenuItem(
                          value: URL.readmeUrl, child: new Text("使用教程")),
                      new PopupMenuItem(
                          value: URL.getIPUrl, child: new Text("获取IP"))
                    ])
          ],
        ),
        body: Builder(
            builder: (context) => GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () {
                  // 触摸收起键盘
                  FocusScope.of(context).unfocus();
                },
                child: Center(
                    child: Form(
                        key: _formKey,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Padding(
                                padding: EdgeInsets.all(15),
                                child: TextFormField(
                                    controller: _ipController,
                                    decoration: ViewCreator.createDecoration(
                                        "IP地址", "合法的IP地址"),
                                    validator: (v) {
                                      if (isDimiIp(v.trim())) {
                                        return null;
                                      } else {
                                        return "不是合法的IP地址";
                                      }
                                    })),
                            Padding(
                                padding: EdgeInsets.all(15),
                                child: GestureDetector(
                                    behavior: HitTestBehavior.translucent,
                                    onTap: () {
                                      // 触摸收起键盘
                                      FocusScope.of(context).unfocus();
                                    },
                                    child: TextFormField(
                                        controller: _userController,
                                        maxLines: 2,
                                        decoration: ViewCreator.createDecoration(
                                            "用户信息",
                                            "形如{'name':'xxx','phone':'12345','id':111}的用户信息"),
                                        validator: (v) {
                                          if (isUserInfo(v.trim())) {
                                            return null;
                                          } else {
                                            return "用户信息解析失败";
                                          }
                                        }))),
                            MaterialButton(
                                color: Colors.blue,
                                highlightColor: Colors.blue[700],
                                colorBrightness: Brightness.dark,
                                splashColor: Colors.grey,
                                textColor: Colors.white,
                                child: Text("连接"),
                                onPressed: () {
                                  if ((_formKey.currentState as FormState)
                                      .validate()) {
                                    login(context, _ipController.text,
                                        _userController.text);
                                  }
                                }),
                            Padding(
                                padding: EdgeInsets.only(top: 10),
                                child: GestureDetector(
                                  child: Text("获取用户信息",
                                      style: TextStyle(color: Colors.blue)),
                                  onTap: () => push(context, Login()),
                                ))
                          ],
                        ))))));

    Bridge.getIp().then((value) => _ipController.text = value);
    Bridge.getUserInfo().then((value) => _userController.text = value);

    return view;
  }

  void login(BuildContext context, String ip, String user) {
    LoadingDialog.showLoading(context, "正在认证网络");

    Api.wifiLogin(ip, jsonDecode(user), success: () {
      Navigator.pop(context);
      FocusScope.of(context).requestFocus(FocusNode());
      showSnack(context, "认证成功");
      Bridge.saveUserInfo(user);
    }, error: (e) {
      Navigator.pop(context);
      showSnack(context, e);
    });
  }

  bool isDimiIp(String str) {
    return RegExp('^17\\d{1}(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}\$')
        .hasMatch(str);
  }

  bool isUserInfo(String text) {
    try {
      Map<String, dynamic> js = jsonDecode(text);

      LoginData user = LoginData().fromJson(js);

      if (user.phone == null) {
        return false;
      }
      if (user.id == null) {
        return false;
      }
      if (user.name == null) {
        return false;
      }

      return true;
    } catch (e) {
      return false;
    }
  }

  void showSnack(BuildContext context, String text) {
    SnackBar snackBar = SnackBar(content: Text(text));
    Scaffold.of(context).showSnackBar(snackBar);
  }

  void push(BuildContext context, StatelessWidget view) {
    Navigator.push(context, MaterialPageRoute(builder: (context) => view))
        .then((value) => _userController.text = value);
  }
}
